package edu.jsnu.operate.util;

import org.apache.commons.lang.RandomStringUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

public class CheckCodeUtils {

    /**
     * 后台CMS图片唯一标识(不要重复，不要修改)
     */
    public static final String CMS_IDENTIFY_KEY = "_cms_identify_code_key_";


    /**
     * 获取图片验证码
     */
    public static String getCmsCode(HttpServletRequest request) {
        if (request.getSession().getAttribute(CMS_IDENTIFY_KEY) != null) {
            return request.getSession().getAttribute(CMS_IDENTIFY_KEY).toString();
        } else {
            return null;
        }
    }

    /**
     * 获取验证码
     * @param request
     * @param response
     * @throws IOException
     */
    public static void getCmsCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String random = RandomStringUtils.randomAlphanumeric(4);
        // 将四位数字的验证码保存到session中
        request.getSession().setAttribute(CMS_IDENTIFY_KEY, random);
        response.setContentType("image/jpeg");
        response.addHeader("pragma", "NO-cache");
        response.addHeader("Cache-Control", "no-cache");
        response.addDateHeader("Expries", 0);
        BufferedImage image = new BufferedImage(110, 33, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        //以下填充背景色
        try {
            g.setColor(new Color(225, 225, 225));
            Font DeFont = new Font("SansSerif", Font.PLAIN, 26);
            g.setFont(DeFont);
            g.fillRect(0, 0, 110, 33);
            //设置字体色
            g.setColor(Color.BLACK);
            g.drawString(random, 20, 25);
            g.dispose();
            ServletOutputStream outStream = response.getOutputStream();
            ImageIO.write(image, "JPG", outStream);
            outStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
